<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>goroutine - 古一 - 个人博客</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="古一" /><meta name="description" content="1. 生成器语法 生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 yield 生成多个想要的值。 任何包含 yield 的函数都是一个生成器函数。 当" /><meta name="keywords" content="古一, 博客, 网站" />






<meta name="generator" content="Hugo 0.81.0 with theme even" />


<link rel="canonical" href="/post/php/%E7%94%9F%E6%88%90%E5%99%A8/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.af7fd1da18d66c2b017df5b4cae508ef44cfcac3fb4c7c7a327fe4f4f9e28b08.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="goroutine" />
<meta property="og:description" content="1. 生成器语法 生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 yield 生成多个想要的值。 任何包含 yield 的函数都是一个生成器函数。 当" />
<meta property="og:type" content="article" />
<meta property="og:url" content="/post/php/%E7%94%9F%E6%88%90%E5%99%A8/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2021-09-14T13:08:00&#43;08:00" />
<meta property="article:modified_time" content="2021-09-14T14:15:00&#43;08:00" />

<meta itemprop="name" content="goroutine">
<meta itemprop="description" content="1. 生成器语法 生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 yield 生成多个想要的值。 任何包含 yield 的函数都是一个生成器函数。 当"><meta itemprop="datePublished" content="2021-09-14T13:08:00&#43;08:00" />
<meta itemprop="dateModified" content="2021-09-14T14:15:00&#43;08:00" />
<meta itemprop="wordCount" content="1154">
<meta itemprop="keywords" content="PHP," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="goroutine"/>
<meta name="twitter:description" content="1. 生成器语法 生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 yield 生成多个想要的值。 任何包含 yield 的函数都是一个生成器函数。 当"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">古一</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">文章</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/about/">
        <li class="mobile-menu-item">关于</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">古一</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">文章</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/">关于</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">goroutine</h1>

      <div class="post-meta">
        <span class="post-time"> 2021-09-14 </span>
        <div class="post-category">
            <a href="/categories/%E6%8A%80%E6%9C%AF/"> 技术 </a>
            </div>
          <span class="more-meta"> 约 1154 字 </span>
          <span class="more-meta"> 预计阅读 3 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li>
          <ul>
            <li><a href="#1-生成器语法">1. 生成器语法</a></li>
            <li><a href="#2-yield关键字">2. <strong>yield</strong>关键字</a></li>
            <li><a href="#3-示例">3. 示例</a></li>
            <li><a href="#4-概念理解">4. 概念理解</a></li>
            <li><a href="#5-应用场景">5. 应用场景</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <h3 id="1-生成器语法">1. 生成器语法</h3>
<p>生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 <a href="https://www.php.net/manual/zh/language.generators.syntax.php#control-structures.yield">yield</a> 生成多个想要的值。 任何包含 <a href="https://www.php.net/manual/zh/language.generators.syntax.php#control-structures.yield">yield</a> 的函数都是一个生成器函数。</p>
<p>当一个生成器被调用的时候，它返回一个可以被遍历的对象.当你遍历这个对象的时候(例如通过一个<a href="https://www.php.net/manual/zh/control-structures.foreach.php">foreach</a>循环)，PHP 将会在每次需要值的时候调用对象的遍历方法，并在产生一个值之后保存生成器的状态，这样它就可以在需要产生下一个值的时候恢复调用状态。</p>
<p>一旦不再需要产生更多的值，生成器可以简单退出，而调用生成器的代码还可以继续执行，就像一个数组已经被遍历完了。</p>
<h3 id="2-yield关键字">2. <strong>yield</strong>关键字</h3>
<p>生成器函数的核心是<strong>yield</strong>关键字。它最简单的调用形式看起来像一个return申明，不同之处在于普通return会返回值并终止函数的执行，而yield会返回一个值给循环调用此生成器的代码并且只是暂停执行生成器函数。</p>
<h3 id="3-示例">3. 示例</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-php" data-lang="php"><span class="o">&lt;?</span><span class="nx">php</span>

<span class="k">function</span> <span class="nf">xrange</span><span class="p">(</span><span class="nv">$start</span><span class="p">,</span> <span class="nv">$limit</span><span class="p">,</span> <span class="nv">$step</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nv">$start</span> <span class="o">&lt;=</span> <span class="nv">$limit</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$step</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">LogicException</span><span class="p">(</span><span class="s1">&#39;Step must be positive&#39;</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="k">print</span> <span class="s1">&#39;xrange - start&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
        <span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="o">=</span> <span class="nv">$start</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">&lt;=</span> <span class="nv">$limit</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">+=</span> <span class="nv">$step</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">print</span> <span class="s1">&#39;xrange - yielding...&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
            <span class="k">yield</span> <span class="nv">$i</span><span class="p">;</span>
            <span class="k">print</span> <span class="s1">&#39;xrange - continued...&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">print</span> <span class="s1">&#39;xrange - end&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="nv">$step</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nx">LogicException</span><span class="p">(</span><span class="s1">&#39;Step must be negative&#39;</span><span class="p">);</span>
        <span class="p">}</span>
        <span class="k">print</span> <span class="s1">&#39;xrange - start&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
        <span class="k">for</span> <span class="p">(</span><span class="nv">$i</span> <span class="o">=</span> <span class="nv">$start</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">&gt;=</span> <span class="nv">$limit</span><span class="p">;</span> <span class="nv">$i</span> <span class="o">+=</span> <span class="nv">$step</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">print</span> <span class="s1">&#39;xrange - yielding...&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
            <span class="k">yield</span> <span class="nv">$i</span><span class="p">;</span>
            <span class="k">print</span> <span class="s1">&#39;xrange - continued...&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">print</span> <span class="s1">&#39;xrange - end&#39;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>

    <span class="p">}</span>
<span class="p">}</span>

<span class="k">echo</span> <span class="s1">&#39;Single digit odd numbers from range():  &#39;</span><span class="o">.</span><span class="nx">PHP_EOL</span><span class="p">;</span>
<span class="k">foreach</span> <span class="p">(</span><span class="nx">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="k">as</span> <span class="nv">$number</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">echo</span> <span class="s2">&#34;</span><span class="si">$number</span><span class="s2"> &#34;</span><span class="o">.</span><span class="nx">PHP_EOL</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">echo</span> <span class="s2">&#34;</span><span class="se">\n</span><span class="s2">&#34;</span><span class="p">;</span>

<span class="k">echo</span> <span class="s1">&#39;Single digit odd numbers from xrange(): &#39;</span><span class="o">.</span><span class="nx">PHP_EOL</span><span class="p">;</span>
<span class="k">foreach</span> <span class="p">(</span><span class="nx">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="k">as</span> <span class="nv">$number</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">print</span> <span class="s2">&#34;Getting current value from the generator...&#34;</span> <span class="o">.</span> <span class="nx">PHP_EOL</span><span class="p">;</span>
    <span class="k">echo</span> <span class="s2">&#34;</span><span class="si">$number</span><span class="s2"> &#34;</span><span class="o">.</span><span class="nx">PHP_EOL</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>测试结果</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-fallback" data-lang="fallback">Single digit odd numbers from range():  
1 
3 
5 
7 
9 

Single digit odd numbers from xrange(): 
xrange - start
xrange - yielding...
Getting current value from the generator...
1 
xrange - continued...
xrange - yielding...
Getting current value from the generator...
3 
xrange - continued...
xrange - yielding...
Getting current value from the generator...
5 
xrange - continued...
xrange - yielding...
Getting current value from the generator...
7 
xrange - continued...
xrange - yielding...
Getting current value from the generator...
9 
xrange - continued...
xrange - end
</code></pre></td></tr></table>
</div>
</div><h3 id="4-概念理解">4. 概念理解</h3>
<p>首先明确一个概念：<strong>生成器yield关键字不是返回值，他的专业术语叫产出值，只是生成一个值</strong></p>
<p>那么代码中<code>foreach</code>循环的是什么？其实是PHP在使用生成器的时候，会返回一个<code>Generator</code>类的对象。<code>foreach</code>可以对该对象进行迭代，每一次迭代，PHP会通过<code>Generator</code>实例计算出下一次需要迭代的值。这样<code>foreach</code>就知道下一次需要迭代的值了。</p>
<p>而且，在运行中<code>for</code>循环执行后，会立即停止。等待<code>foreach</code>下次循环时候再次和<code>for</code>索要下次的值的时候，<code>for</code>循环才会再执行一次，然后立即再次停止。直到不满足条件不执行结束。</p>
<h3 id="5-应用场景">5. 应用场景</h3>
<ul>
<li>
<h4 id="读取超大文件">读取超大文件</h4>
</li>
</ul>
<p>PHP开发很多时候都要读取大文件，比如csv文件、text文件，或者一些日志文件。这些文件如果很大，比如5个G。这时，直接一次性把所有的内容读取到内存中计算不太现实。使用生成器读取文件，第一次读取了第一行，第二次读取了第二行，以此类推，<strong>每次被加载到内存中的文字只有一行</strong>，大大的减小了内存的使用。这样，即使读取上G的文本也不用担心，完全可以像读取很小文件一样编写代码。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">古一</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2021-09-14
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content">MIT</span>
  </p>
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/php/">PHP</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/golang/goroutine/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">goroutine</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/php/curl%E7%B1%BB/">
            <span class="next-text nav-default">CURL类</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
  <a href="/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    <span><a href="https://beian.miit.gov.cn/">粤ICP备20006718号-1</a></span>
    &copy; 
    2018 - 
    2022<span class="heart"><i class="iconfont icon-heart"></i></span><span>古一</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        }
    };
  </script>
  <script async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js" integrity="sha256-HGLuEfFcsUJGhvB8cQ8nr0gai9EucOOaIxFw7qxmd+w=" crossorigin="anonymous"></script>








</body>
</html>
